package fw.qaz.asmx.reader.utils;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public final class FileProcess
{
    /**
     * 读取文件
     *
     * @param name 提供完整文件路径字符串
     * @return 以字节数组返回读取结果
     */
    public static byte[] readFile(String name)
    {
        File f = new File(name);
        byte[] bt = new byte[4096];
        if (f.exists())
        {
            try
            {
                FileInputStream fis = new FileInputStream(f);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while (true)
                {
                    int cnt = fis.read(bt);
                    if (cnt > 0)
                    {
                        baos.write(bt);
                        continue;
                    }
                    break;
                }
                baos.flush();
                byte[] data = baos.toByteArray();
                baos.close();
                fis.close();
                return data;
            }
            catch (Exception e)
            {
                Log.e("FW Reader - readFile", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 写入文件
     *
     * @param name    完整文件路径字符串
     * @param content 文件内容字节数组
     * @param append  是否在当前文件尾部写入
     * @return 返回写入结果，false表示写入失败
     */
    public static boolean writeFile(String name, byte[] content, boolean append)
    {
        File f = new File(name);

        try
        {
            if (!f.exists() && !f.createNewFile())
            {
                return false;
            }
            FileOutputStream fos = new FileOutputStream(f, append);
            fos.write(content);
            fos.flush();
            fos.close();
            return true;
        }
        catch (Exception e)
        {
            Log.e("FW Reader - writeFile", e.getMessage());
            return false;
        }
    }
}
